
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_sample/src/log_util.dart';
import 'package:go_router/go_router.dart';

const String CHANNEL_NAME = 'com.michaeliu.flutter.study/method_channel';

class MethodChannelPage extends StatefulWidget {
  const MethodChannelPage({super.key});

  @override
  State<MethodChannelPage> createState() => _MethodChannelPageState();
}

class _MethodChannelPageState extends State<MethodChannelPage> {

  late MethodChannel channel;
  
  @override
  void initState() {
    super.initState();
    channel = MethodChannel(CHANNEL_NAME);
    // 监听来自 Android端 的消息通道
    // Android端调用了函数，这个handler函数就会被触发
    channel.setMethodCallHandler((MethodCall call) {
      String methodName = call.method;
      logger.i(methodName);
      switch(methodName) {
        case "sendToFlutter" :
          return Future.value("Flutter 端接收 Android 端 sendToFlutter 成功");
        case "getFromFlutter" :
          return Future.value("Flutter 端接收 Android 端 getFromFlutter 成功");
      }

      return Future.value(true);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("MethodChannel"),
          centerTitle: true,
          leading: IconButton(
            onPressed: () {
              context.pop();
            },
            icon: Icon(Icons.arrow_back_ios_rounded),
          ),
        ),
      body: Column(
        children: [
          ElevatedButton(onPressed: () {
            sendToAndroid();
          }, child: Text("Android 调用原生方法")),
          ElevatedButton(onPressed: () {
            getFromAndroid();
          }, child: Text("Android 调用原生方法并获取数据")),
        ],
      ),
    );
  }


  sendToAndroid () {
    channel.invokeMethod("send").then((ret) {
      logger.i(ret);
    }).catchError((error) {});
  }

  getFromAndroid() {
    channel.invokeMethod("get").then((ret) {
      logger.i(ret);
    }).catchError((error) {});
  }

}
